package com.juanpi.order.common.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by fu.wan on 2014/4/16.
 */
public final class JsonMapper {

	/**
	 * ���캯��
	 */
	private JsonMapper() {
	}

	/**
	 * Object������POJO��Ҳ������Collection�����顣 ������ΪNull, ����"null". ����Ϊ�ռ���, ����"[]".
	 */
	public static String toJson(Object object) {
		return JSON.toJSONString(object, SerializerFeature.WriteMapNullValue,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNonStringKeyAsString);
	}

	/**
	 * Object������POJO��Ҳ������Collection�����顣 ������ΪNull, ����"null". ����Ϊ�ռ���, ����"[]".
	 */
	public static String toJsonFormat(Object object) {
		return JSON.toJSONString(object, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNonStringKeyAsString);
	}

	/**
	 * Object������POJO��Ҳ������Collection�����顣
	 * 
	 * @param obj
	 * @return ����ԭʼjson Object����
	 */
	public static Object toJsonObject(Object obj) {
		return JSON.toJSON(obj);
	}

	/**
	 * �����л�POJO���Collection��List<String>.
	 * <p/>
	 * ���JSON�ַ�ΪNull��"null"�ַ�, ����Null. ���JSON�ַ�Ϊ"[]", ���ؿռ���.
	 * <p/>
	 * ���跴���л�����Collection��List<MyBean>, ��ʹ��fromJson(String, JavaType)
	 */
	public static <T> T fromJson(String jsonString, Class<T> clazz) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		return JSON.parseObject(jsonString, clazz);
	}

	/**
	 *
	 * @param jsonString
	 *            JSON�ַ�
	 * @return
	 * @throws Exception
	 */
	public static <T> T fromJson(String jsonString) throws Exception {
		return JSON.parseObject(jsonString, new TypeReference<T>() {
		});
	}
}
